package com.lys.controller;

import com.lys.entity.Product;
import com.lys.entity.ProductCategory;
import com.lys.param.ProductCategoryParam;
import com.lys.service.ProductCategoryService;
import com.lys.service.ProductService;
import com.lys.utils.EmptyUtils;
import com.lys.utils.Pager;
import com.lys.utils.ReturnResult;
import com.lys.utils.StringUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author 陆小根
 * @version 9.0.4
 * @Date 2022/5/30 8:57
 */
@Controller
@RequestMapping("/admin/product")
public class AdminProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService productCategoryService;

    private static final String TMP_DIR_PATH = "c:\\tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "/files";
    private File destinationDir;

    /**
     * 商品的主页面
     * @return
     */
    @GetMapping("/index")
    public String index(@RequestParam(value = "currentPage",required = false) String currentPageStr,
                        @RequestParam(value = "pageSize",required = false) String pageSize,
                        Model model){
        //获取当前页数
        // String currentPageStr = request.getParameter("currentPage");
        //获取页大小
        // String pageSize = request.getParameter("pageSize");
        int rowPerPage  = EmptyUtils.isEmpty(pageSize)?5:Integer.parseInt(pageSize);
        int currentPage = EmptyUtils.isEmpty(currentPageStr)?1:Integer.parseInt(currentPageStr);
        int total=productService.count(null, null, null);
        Pager pager=new Pager(total,rowPerPage,currentPage);
        pager.setUrl("admin/product/index");
        List<Product> productList=productService.getProductList(currentPage,rowPerPage, null, null, null);
        model.addAttribute("productList", productList);
        model.addAttribute("pager", pager);
        model.addAttribute("menu",5);
        return "/backend/product/productList";
    }
    /**
     * 跳转到添加商品
     * @return
     */
    @GetMapping("/toAdd")
    public String toAddProduct(Model model) {
        model.addAttribute("menu",6);
        model.addAttribute("product",new Product());
        //查询一级分类
        ProductCategoryParam params =new ProductCategoryParam();
        params.setType(1);
        List<ProductCategory> productCategoryList=productCategoryService.queryProductCategoryList(params);
        //一级分类列表
        model.addAttribute("productCategoryList1", productCategoryList);
        return "/backend/product/toAddProduct";
    }
    /**
     * 添加和修改商品
     * @throws Exception
     */
    @PostMapping("/saveOrUpdate")
    public String addProduct(Product product,
                             MultipartFile photo,
                             HttpSession session) {

        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.exists()) {//如果目录不存在，则新建目录
            tmpDir.mkdirs();
        }
        // 通过ServletContext获取服务器photo目录的路径
        String realPath = session.getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
        if (!destinationDir.exists()) {
            destinationDir.mkdirs();
        }
        String fileName = photo.getOriginalFilename();
        if (fileName != null && !fileName.equals("")) {
            String suffiexName = fileName.substring(fileName.lastIndexOf("."));
            // 将UUID作为文件的名 ----> 解决重名问题
            String uuid = UUID.randomUUID().toString();
            // 将uuid何后缀名拼接后的记过作为最终的文件名
            fileName = uuid + suffiexName;

            String destPath = destinationDir + File.separator + fileName;
            // 读写图片
            try {
                photo.transferTo(new File(destPath));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            //获取商品参数
            product.setFileName(fileName);
        }
        Integer id = product.getId();
        if (EmptyUtils.isEmpty(id) || id.equals("0")) {
            productService.add(product);
        } else {
            if(EmptyUtils.isEmpty(product.getFileName())|| product.getFileName().length()<5){
                Product productDemo=productService.getProductById(id);
                product.setFileName(productDemo.getFileName());
            }
            productService.update(product);
        }

        return "redirect:/admin/product/index";
    }
    /**
     * 跳转到修改页面商品
     * @return
     */
    @GetMapping("/toUpdate")
    public String toUpdateProduct(@RequestParam("id") String id,
                                  Model model) {
        // String id=request.getParameter("id");
        Product product=productService.getProductById(Integer.valueOf(id));
        model.addAttribute("menu",6);
        //查询一级分类
        ProductCategoryParam params =new ProductCategoryParam();
        params.setType(1);
        List<ProductCategory> productCategoryList1=productCategoryService.queryProductCategoryList(params);
        params.setType(2);
        List<ProductCategory> productCategoryList2=productCategoryService.queryProductCategoryList(params);
        params.setType(3);
        List<ProductCategory> productCategoryList3=productCategoryService.queryProductCategoryList(params);
        //一级分类列表
        model.addAttribute("productCategoryList1", productCategoryList1);
        model.addAttribute("productCategoryList2", productCategoryList2);
        model.addAttribute("productCategoryList3", productCategoryList3);
        model.addAttribute("product", product);
        return "/backend/product/toAddProduct";
    }
    /**
     * 根据id删除商品
     * @return
     * @throws Exception
     */
    public ReturnResult deleteById(@RequestParam("id") String id) {
        ReturnResult result=new ReturnResult();
        // String id=request.getParameter("id");
        productService.deleteProductById(Integer.parseInt(id));
        result.returnSuccess();
        return result;
    }

    private Product copyToProduct(Map<String,String> params)throws Exception{
        Product product=new Product();
        String id=params.get("id");
        String name=params.get("name");
        String description=params.get("description");
        String price=params.get("price");
        String stock=params.get("stock");
        String categoryLevel1Id=params.get("categoryLevel1Id");
        String categoryLevel2Id=params.get("categoryLevel2Id");
        String categoryLevel3Id=params.get("categoryLevel3Id");
        product.setName(name);
        product.setDescription(description);
        product.setPrice(Float.valueOf(price));
        product.setStock(Integer.parseInt(stock));
        product.setCategoryLevel1Id(EmptyUtils.isNotEmpty(categoryLevel1Id)?Integer.parseInt(categoryLevel1Id):0);
        product.setCategoryLevel2Id(EmptyUtils.isNotEmpty(categoryLevel2Id)?Integer.parseInt(categoryLevel2Id):0);
        product.setCategoryLevel3Id(EmptyUtils.isNotEmpty(categoryLevel3Id)?Integer.parseInt(categoryLevel3Id):0);
        product.setId(EmptyUtils.isNotEmpty(id)?Integer.parseInt(id):null);
        return product;
    }

}
